package com.zbangmall.util.crypt.symmetric;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

public class DesCrypt {


	/**
	 * DES加密
	 *
	 * @param encryptStr 待加密的字符串
	 * @param password   秘钥字符串，最小字节数组长度是8
	 *                   示例：String password = "12345678";
	 * @return 加密后的字符串(这个加密后的字符串是：由加密的字节数组转成Base64编码的字符串)
	 */
	public static String encrypt(String encryptStr, String password) {
		try {
			Cipher cipher = Cipher.getInstance("DES");

			// 【1】获取对称加密的秘钥
			Key key = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(password.getBytes()));

			// 【2】加密模式
			cipher.init(Cipher.ENCRYPT_MODE, key);

			// 【3】获取加密字节数组(注意这个数组的长度是8的整数倍，所有秘钥字节数组的最小也是8)
			byte[] encryptBytes = cipher.doFinal(encryptStr.getBytes());

			//DES加密后编码表找不到对应的字符，对加密后的字节数据进行Base64编码
			return java.util.Base64.getEncoder().encodeToString(encryptBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * DES解密
	 *
	 * @param encryptStr 待解密的字符串(这个待解密字符串是：由加密的字节数组转成Base64编码的字符串)
	 * @param password   秘钥字符串，最小字节数组长度是8
	 * @return 解密后的字符串
	 */
	public static String decrypt(String encryptStr, String password) {
		try {
			//解密前，对密文进行Base64解码
			byte[] encryptBytes = java.util.Base64.getDecoder().decode(encryptStr);

			Cipher cipher = Cipher.getInstance("DES");

			// 【1】获取对称加密的秘钥
			Key key = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(password.getBytes()));

			// 【2】解密模式
			cipher.init(Cipher.DECRYPT_MODE, key);

			// 【3】获取解密字节数组
			byte[] decryptBytes = cipher.doFinal(encryptBytes);

			return new String(decryptBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


}
